package com.clw.template.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clw.template.bo.AdminUserDetails;
import com.clw.template.entity.SysAdmin;
import com.clw.template.entity.SysAdminLoginLog;
import com.clw.template.entity.SysRolePermissionRelation;
import com.clw.template.mapper.SysAdminMapper;
import com.clw.template.service.ISysAdminLoginLogService;
import com.clw.template.service.ISysAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clw.template.service.ISysRolePermissionRelationService;
import com.clw.template.util.JwtTokenUtil;
import com.clw.template.util.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author clw
 * @since 2019-11-01
 */
@Service
public class SysAdminServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements ISysAdminService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysAdminServiceImpl.class);

    @Autowired
    private SysAdminMapper sysAdminMapper;
    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private ISysAdminLoginLogService sysAdminLoginLogService;
    @Autowired
    private ISysRolePermissionRelationService sysRolePermissionRelationService;



    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
            insertLoginLog();
        } catch (AuthenticationException e){
            LOGGER.warn("登录异常：{}",e.getMessage());
        }
        return token;
    }

    @Override
    public SysAdmin getLoginUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
        AdminUserDetails adminUserDetails = (AdminUserDetails) authenticationToken.getPrincipal();
        return adminUserDetails.getSysAdmin();
    }

    @Override
    public void deleted(Long id) {
        removeById(id);
    }

    @Override
    public IPage<SysAdmin> userList(Integer pageNum, Integer pageSize) {
        Page<SysAdmin> page = new Page<>(pageNum,pageSize);
        return page(page);
    }

    @Override
    public void updatePassword(Long id, String password) {
        SysAdmin admin = new SysAdmin();
        admin.setId(id);
        admin.setPassword(passwordEncoder.encode(password));
        updateById(admin);
    }

    /**
     * 添加登录记录
     */
    private void insertLoginLog() {
        SysAdmin admin = getLoginUserInfo();
        SysAdminLoginLog loginLog = new SysAdminLoginLog();
        loginLog.setAdminId(admin.getId());
        loginLog.setCreateTime(LocalDateTime.now());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        loginLog.setIp(SystemUtils.getIpAddress(request));
        loginLog.setUserAgent(request.getHeader("user-agent"));
        sysAdminLoginLogService.save(loginLog);
    }

}
